package com.milorad.ads.pages.admin;

import java.util.StringTokenizer;

import javax.servlet.http.Cookie;

import org.apache.wicket.Session;
import org.apache.wicket.markup.html.form.CheckBox;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.TextArea;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.html.panel.FeedbackPanel;
import org.apache.wicket.model.CompoundPropertyModel;
import org.apache.wicket.spring.injection.annot.SpringBean;

import com.milorad.ads.data.dao.interfaces.UserDao;
import com.milorad.ads.data.domain.User;
import com.milorad.ads.pages.BasePage;
import com.milorad.ads.session.UserSession;

/**
 * Log in page for Administration panel.
 * 
 * @author Milorad
 */
public class LoginPage extends BasePage {
	
	private static boolean initFlag = false;
	
	@SpringBean
	private UserDao userDao;
	
	
	/**
	 * Constructor
	 */
	public LoginPage() {
		
		insertAdmin();
		
		if ((((UserSession)Session.get()).getUserData() != null) || userAutheticatedViaCookie()) {
			// user already logged in
			setResponsePage(MainAdminPage.class);	
		}						
		
		add(createLogInForm());	
		
		add(new FeedbackPanel("feedback"));				
	}

	private Form<User> createLogInForm() {
		
		Form<User> form = new Form<User>("loginForm", new CompoundPropertyModel<User>(new User())) {

			private static final long serialVersionUID = 1L;

			@Override
			protected void onSubmit() {				
				
				User user = getModelObject();								
								
				User userFromDb = userDao.findByUsername(user.getUsername());
				
				if ((userFromDb == null) || (!userFromDb.getPassword().equals(user.getPassword()))) {																	
					error("Wrong user name or password.");					
				} else  {
					// user and pass OK
					if (user.isRememberMe()) {
						logInUser(userFromDb);
					}
					setResponsePage(MainAdminPage.class);				
				}
			}			
		};
		
		form.add(new TextField<User>("username").setRequired(true));
		form.add(new TextArea<User>("password").setRequired(true));
		form.add(new CheckBox("rememberMe"));
		return form;
	}
	
	/**
	 * Registers user in session, and creates cookie.
	 * 
	 * @param userFromDb - authenticated user
	 */
	private void logInUser(User userFromDb) {
		
		String authenticationToken = String.valueOf(System.currentTimeMillis());
		userFromDb.setAuthenticationToken(authenticationToken);
		
		userDao.save(userFromDb);
		
		((UserSession)Session.get()).setUserData(userFromDb);				
		
		getWebRequestCycle().getWebResponse().addCookie(new Cookie("smallAds", userFromDb.getUsername()+"#"+authenticationToken));
	}		
	
	/**
	 * User is successfully recognized via cookie.
	 * @return true if user is autheticated
	 */
	private boolean userAutheticatedViaCookie() {
		
		Cookie cookie = getWebRequestCycle().getWebRequest().getCookie("smallAds");
		if (cookie != null) {
			String cookieValue = cookie.getValue();
			StringTokenizer tokenizer = new StringTokenizer(cookieValue, "#");
			String username = tokenizer.nextToken();
			String authenticationToken = tokenizer.nextToken();
			
			User user = userDao.findByUsername(username);
			
			if (authenticationToken.equals(user.getAuthenticationToken())) {
				
				UserSession userSession = (UserSession)Session.get();								
				userSession.setUserData(user);
				return true;
			}
		}
		
		return false;
	}
	
	private void insertAdmin() {
		
		if (initFlag == false) {
		
			User adminUser = new User();
			adminUser.setUsername("admin");
			adminUser.setPassword("admin");
			adminUser.setFirstName("Milorad");
			adminUser.setLastName("Zdravkovic");
		
			userDao.save(adminUser);
			initFlag=true;
		}
		
	}
}